package com.hotlcc.bark.common.aop;

import cn.hutool.core.io.IoUtil;
import cn.hutool.json.JSONUtil;
import com.hotlcc.bark.common.bean.RestResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.io.IOException;
import java.lang.annotation.*;

/**
 * 统一返回结果增强
 */
@RestControllerAdvice
@Slf4j
public class ResponseBodyAdviceImpl implements ResponseBodyAdvice<Object> {
    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {
        return !returnType.getGenericParameterType().equals(RestResult.class)
            && !returnType.hasMethodAnnotation(Unsupported.class);
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        RestResult result;
        if (returnType.getGenericParameterType().equals(Void.class)) {
            result = RestResult.success();
        } else {
            result = RestResult.success(body);
        }

        response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
        try {
            IoUtil.writeUtf8(response.getBody(), true, JSONUtil.toJsonStr(result));
        } catch (IOException e) {
            log.error("IO异常", e);
        }

        return body;
    }

    @Target(ElementType.METHOD)
    @Retention(RetentionPolicy.RUNTIME)
    @Documented
    public @interface Unsupported {

    }
}
